package com.tzy.rpc.transport.netty.server;/**
 * @description:
 * @Author HP
 * @create 2022/3/14 19:54
 */

import com.tzy.rpc.codec.CommonDecoder;
import com.tzy.rpc.codec.CommonEncoder;
import com.tzy.rpc.hook.ShutdownHook;
import com.tzy.rpc.provider.ServiceProviderImpl;
import com.tzy.rpc.register.NacosServiceRegistry;
import com.tzy.rpc.serializer.CommonSerializer;
import com.tzy.rpc.transport.AbstractRpcServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author HP
 * @create 2022-03-14 19:54
 * @desc 用netty实现server
 **/
public class NettyServer extends AbstractRpcServer {

    private CommonSerializer serializer;

    public NettyServer() {
    }

    public NettyServer(String host, int port) {
        this.host = host;
        this.port = port;
        serviceProvider=new ServiceProviderImpl();
        serviceRegistry=new NacosServiceRegistry();
        //自动注册服务
        scanServices();
    }

    @Override
    public void start() {
        //添加注销服务的钩子，服务端关闭时才会执行
        ShutdownHook.getShutdownHook().addClearAllHook();
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG,256)
                    .option(ChannelOption.SO_KEEPALIVE,true)
                    .childOption(ChannelOption.TCP_NODELAY,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new IdleStateHandler(10,0,0, TimeUnit.SECONDS))
                                    .addLast(new CommonEncoder(serializer))
                                    .addLast(new CommonDecoder())
                                    .addLast(new NettyServerHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(host,port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            logger.error("启动服务器时有错误发生", e);
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @Override
    public void setSerializer(CommonSerializer serializer) {
        this.serializer=serializer;
    }

}
